package com.chao.deeply.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author : Rookie
 * @description :
 * @date : 2023/8/7
 */
public class CyclicBarrierTest {
    // 3个线程一组
    private static final int nums = 3;
    // 每完成nums，执行一次TeacherTask
    public static final CyclicBarrier cyclicBarrier = new CyclicBarrier(nums,new TeacherTask());

    public static void main(String[] args) {
        for (int i = 0; i < nums; i++) {
            new Thread(new StudentTask(cyclicBarrier,i),"t" + i).start();
        }
    }


}

class StudentTask implements Runnable {

    private CyclicBarrier cyclicBarrier;

    private volatile Integer studentNum;

    public StudentTask(CyclicBarrier cyclicBarrier,Integer num) {
        this.cyclicBarrier = cyclicBarrier;
        this.studentNum = num;
    }

    @Override
    public void run() {
        System.out.println("线程" + studentNum + "执行第1组动作");
        try {
            // 等待所有线程执行完第一组动作
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println("线程" + studentNum + "执行第2组动作");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

class TeacherTask implements Runnable {

    @Override
    public void run() {
        System.out.println("====执行教师动作====");
    }
}
